package com.qfedu.food.service.impl;

import com.qfedu.food.config.RedisKeyConfig;
import com.qfedu.food.config.SystemConfig;
import com.qfedu.food.dao.TSmsLogDao;
import com.qfedu.food.dto.TSmsCodeDto;
import com.qfedu.food.pojo.TSmsLog;
import com.qfedu.food.service.intf.TSmsLogService;
import com.qfedu.food.util.AliSmsUtil;
import com.qfedu.food.util.NumRandomUtil;
import com.qfedu.food.util.RedissonUtil;
import com.qfedu.food.util.StringUtil;
import com.qfedu.food.vo.R;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class TSmsLogServiceImpl implements TSmsLogService {
    @Autowired
    private TSmsLogDao dao;

    @Override
    public R queryAll() {
        return R.ok(dao.selectAll());
    }

    @Override
    public R sendCode(String phone) {
        // 非法参数校验
        if (StringUtil.isNoEmpty(phone)){
            // 生成验证码
            int code = NumRandomUtil.createRandomNum(SystemConfig.SMS_CODELEN);
            // 发送短信
            if (AliSmsUtil.sendSmsCode(phone,code)){
                // 验证码 10分钟有效期
                RedissonUtil.setStr(RedisKeyConfig.SMS_CODE + phone,code,RedisKeyConfig.SMS_CODE_TIMES);
                // 记录数据到数据库
                dao.insert(new TSmsLog(phone,SystemConfig.SMS_CODEADD,phone + "注册新用户，短信验证码"));
                return R.ok();
            }
        }
        return R.fail();
    }

    @Override
    public R checkCode(TSmsCodeDto dto) {
        // 参数的非法校验
        if (dto != null){
            if (StringUtil.isNoEmpty(dto.getPhone()) && dto.getCode() > 0){
                String key = RedisKeyConfig.SMS_CODE + dto.getPhone();
                // 验证Redis key是否存在
                if (RedissonUtil.isHave(key)){
                    // 校验是否正确
                    if (dto.getCode() == Integer.parseInt(RedissonUtil.getStr(key))){
                        return R.ok();
                    }
                }
            }
        }
        return R.fail();
    }
}
